
var EventEmitter    = require('events').EventEmitter;

var Class           = require('ClassBuilder');

var config          = require('./config.js');

var MessageBuffer   = require('../MessageBuffer');



var MessageSocket = Class(function( _public, _static ) {

    _public._construct = function( socket ) {
        
        var self = this;

        this.messageBuffer = new MessageBuffer();

        this.eventEmitter  = new EventEmitter();

        socket.on( 'data', function(data) {

            console.log('[MessageSocket] Got data stream line:' );
            console.log(data);
            console.log(data.toString());
            console.log('[MessageSocket] End!\n');


            self.messageBuffer.pushChunk( data );
            

            while( self.checkBuffer() );

        });

        socket.setTimeout( config.timeout || 60000 );

        socket.on( 'timeout', function() {
            socket.end();
            socket.destroy();
        });

    };

    _public.on = function( e, fn ) {
        this.eventEmitter.on( e, fn );
    };
    _public.emit = function() {
        this.eventEmitter.emit.apply( this.eventEmitter, arguments );
    };

    _public.checkBuffer = function() {

        var msgBuffOK = this.messageBuffer.selfSizeCheck();

        if( msgBuffOK ) {
            this.emit( 'message', msgBuffOK );
            return true;
        }
        else
            return false;

    };


});



module.exports = MessageSocket;